# encoding: utf-8
class Track
  attr_accessor :tracks
  extend Console
  AUTO_WAY = "使用默认路径"
  MANUAL_WAY = "手动输入路径"
  CHOOSE_WAYS = [AUTO_WAY, MANUAL_WAY]
  AUTO_TRACK = ['AB4', 'BC5', 'DA5', 'CE7']
  class << self
    def get_way
      puts "---------- 请选择获取路径的方式 ----------"
      CHOOSE_WAYS.each_with_index do |way, index|
        puts "#{index.succ} #{way}"
      end
      puts "------------------------------------------"

      input_index = get_input(allows: (1..CHOOSE_WAYS.length).to_a).strip.to_i

      CHOOSE_WAYS.each_with_index do |way,index|
        return way if input_index == index.succ
      end
    end

    def store_track track
      track = track.scan(/\w{2}\d/).first.upcase
      @tracks << track unless @tracks.map{ |d|d[0..1] }.include? track[0..1]
    end

    def init_tracks
      @tracks = []
      @format_tracks = []
      way = get_way
      if way == MANUAL_WAY
        puts "---------- 请输入要录入的路径 以,分割 ----------"
        puts_blue "For example: AB5, AC4, CD6"
        puts "------------------------------------------------"
        get_input.split(/,/).uniq.map { |track| store_track track }
      elsif way == AUTO_WAY
        @tracks = AUTO_TRACK
        AUTO_TRACK.map { |track| store_track track }
      end
      if @tracks.length > 0
        puts "\n获取的路径为\n"
        puts_yellow @tracks.join(", ")
        puts "\n\n 重新选择路径：r(edo) \n 退出： e(xit) \n 回车键继续"

        case get_input(allows: ['r', 'redo', 'e', 'exit'], allow_empty: true)
        when 'r', 'retry'
          get_tracks
          return
        when 'e', 'exit'
          exit
        else end
      end
    end

    def set_tracks
      puts "---------- 请输入要计算的路径 以,分割 ----------"
      puts_blue "For example: ab, abc, abcd, acd, abd"
      puts "------------------------------------------------"
      tracks = get_input.split(/,/).uniq.map { |track| track.scan(/\w+/).first.upcase }
      if tracks.length > 0
        puts "\n需要计算的路径为"
        puts_yellow tracks.join(", ")
        puts "\n\n 重新输入路径：r(edo) \n 退出： e(xit) \n 回车键继续"

        case get_input(allows: ['r', 'redo', 'e', 'exit'], allow_empty: true)
        when 'r', 'retry'
          set_tracks
          return
        when 'e', 'exit'
          exit
        else end
        tracks.map { |track| puts calculate_track track }
      end
    end

    def calculate_track track
      distance = 0
      length = track.length
      track.split('').each_with_index do |v, i|
        next if i == 0
        temp_track = "#{track[i - 1]}#{track[i]}".upcase
        @tracks.each do |t|
          if t.include? temp_track
            distance += t[2].to_i
            length -= 1
          end
        end
      end
      if length == 1
        "#{track}: #{distance}"
      else
        "#{track}: NO SUCH ROUTE"
      end
    end
  end
end
